package ca.uwindsor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.ExpandableListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

public class ViewGrades extends ExpandableListActivity {
List<String> childList = new ArrayList<String>(); //used to store child data.
HashMap<String, String> idArray = new HashMap<String, String>(); //stores the id of the table row to access later
private List<Double> gpaList = new ArrayList<Double>();
private List<Double> creditsList = new ArrayList<Double>();


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//set window title to sem name
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.view_grades);
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.summary);
		//TextView lblSemName = (TextView)findViewById(R.id.lblSemName);
		//lblSemName.setText(Common.globalTerm);
		//TODO:
		//Summary here
		
		
		
		 //Create Expandable lists
		SimpleExpandableListAdapter expListAdapter =
				new SimpleExpandableListAdapter(
					this,
					createGroupList(),	// groupData describes the first-level entries
					R.layout.child_row,	// Layout for the first-level entries
					new String[] { "semester" },	// Key in the groupData maps to display
					new int[] { R.id.lblDay },		// Data under "Day" key goes into this TextView
					createChildList(),	// childData describes second-level entries
					R.layout.child_row,	// Layout for second-level entries
					new String[] { "course", "grade" },	// Keys in childData maps to display
					new int[] { R.id.lblDay, R.id.lblTime }	// Data under the keys above go into these TextViews
				);
			setListAdapter( expListAdapter );
		getExpandableListView().setOnChildClickListener(this);
		
		
		//get cgpa and display.
				TextView lblCGPA = (TextView)findViewById(R.id.txtCGPA);
				lblCGPA.setText("CGPA: "+String.format("%.3f", this.computeCGPA()));		
				
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}
	
	//Creates the Group list and returns
	private List<HashMap<String, String>> createGroupList() {
		
		final MyDBAdapter db = new MyDBAdapter(this);
		db.setDATABASE_TABLE("semester");
		db.open();
		
		
		
		Cursor ret = db.getAllEntries();
		
		
		ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		 
		if(ret.moveToFirst()){
			do{
				//populate the list
				
				HashMap<String, String> m = new HashMap<String, String>();
			    m.put( "semester", ret.getString(1)+"    "+computeGPA(ret.getString(1)));
				result.add( m );
				
				
				//create child list
				
				
				childList.add(ret.getString(1));
				
				
			}while(ret.moveToNext());
		}
		db.close();
		
		  return (List<HashMap<String, String>>)result;
	    }
	
	//Create the child list.
	private List<ArrayList<HashMap<String, String>>> createChildList() {
		
		final MyDBAdapter db = new MyDBAdapter(this);
		db.setDATABASE_TABLE("courses");
		db.open();
		
		Iterator<String> listiter = childList.iterator();
		
		ArrayList<ArrayList<HashMap<String, String>>> result = new ArrayList<ArrayList<HashMap<String, String>>>();
		
		
		while(listiter.hasNext()){
		
		Cursor ret_sch = db.getEntry("sem_name",listiter.next() );
		ArrayList<HashMap<String, String>> secList = new ArrayList<HashMap<String, String>>(); //VOILA!!!!
		
		if(ret_sch.moveToFirst()){
			do{
				
				 	HashMap<String, String> child = new HashMap<String, String>();
					child.put( "course", ret_sch.getString(2) +"  "+ ret_sch.getString(3));
				    child.put( "grade",getLetterGrade(ret_sch.getString(2)));//get grade here
					secList.add( child );
					idArray.put((result.size())+""+(secList.size()-1), ""+ret_sch.getInt(0));

			}while(ret_sch.moveToNext());
			 result.add( secList );
			 
		}else{ 
			//if no grades for course exists alert the user.
			HashMap<String, String> child = new HashMap<String, String>();
			child.put( "course", "No courses added for this semester.");
		    child.put( "grade", "" );
			secList.add( child );
			result.add( secList ); 
		}
		ret_sch.close();
	//add sub list to main list
		}
		 db.close();
		 
		return (List<ArrayList<HashMap<String, String>>>) result;
	  }
	
	/*Return the letter grade for the courses, return N/A if the total marks for course
	 * is less than 100... */
	public String getLetterGrade(String courseCode)
	{
		final MyDBAdapter db = new MyDBAdapter(this);
		db.setDATABASE_TABLE("marks");
		db.open();
		double marksOb = 0;
		double totalMark = 0;
		Cursor getMarks = db.getEntry("course_code",courseCode);
		
		while(getMarks.moveToNext())
		{
			marksOb += getMarks.getDouble(getMarks.getColumnIndex("marks_ob"));
			totalMark += getMarks.getDouble(getMarks.getColumnIndex("weightage"));
		}
		if(totalMark < 100){
			db.close();
			return "N/A";
		}
			
		db.setDATABASE_TABLE("grading");
		
		Cursor getGrade = db.getAllEntries();
		
		while(getGrade.moveToNext()){
			if(marksOb >= getGrade.getDouble(getGrade.getColumnIndex("start_range")) 
					&& marksOb < getGrade.getDouble(getGrade.getColumnIndex("end_range")))
			{
				db.close();
				return getGrade.getString(getGrade.getColumnIndex("letter_grade"));
			}
		}
		db.close();
		return "N/A";
	}
	
	/*Computes the GPA for the given semester*/
	
	public double computeGPA(String semName){
		final MyDBAdapter db = new MyDBAdapter(this);
		db.setDATABASE_TABLE("courses");
		db.open();
		List<String> course = new ArrayList<String>();
		List<Double> credits = new ArrayList<Double>();
		List<Double> creditList2 = new ArrayList<Double>();
		List<String> grades = new ArrayList<String>();
		Cursor courses = db.getEntry("sem_name",semName);
		while(courses.moveToNext())
		{
			course.add(courses.getString(courses.getColumnIndex("course_code")));
			credits.add(courses.getDouble(courses.getColumnIndex("credit")));
		}
		db.close();
		for (int i=0; i<credits.size(); i++)
		{
			String getGrade = getLetterGrade(course.get(i));
			if(!getGrade.equals("N/A"))
			{
				creditList2.add(credits.get(i));
				grades.add(getGrade);
			}
			
		}
		
		
		return calculateGrades(grades, creditList2);
	}
	
	/*calculates the gpa with grades and creits given*/
	private Double calculateGrades(List<String> grades, List<Double> credits)
	{
		final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
		db.setDATABASE_TABLE("grading");
		db.open();
		double gpa = 0;
		double totalCredits = 0;
		List<Double> points = new ArrayList<Double>();
		for(int i=0; i<grades.size(); i++)
		{
			Cursor c = db.getEntry("letter_grade", grades.get(i));
			if(c.moveToNext())
				points.add(c.getDouble(c.getColumnIndex("grade_point")));
		}
		db.close();
		for(int i=0; i<points.size(); i++)
		{
			gpa = gpa + (points.get(i)*credits.get(i));
			totalCredits = totalCredits + credits.get(i);
		}
		gpaList.add(gpa);
		creditsList.add(totalCredits);
		//check if infinity
		if(Double.isNaN(gpa/totalCredits)){
			return 0.0;
		}else{
		return gpa/totalCredits;
		}
	}
	
	/*Calculates the CGPA*/
	public double computeCGPA()
	{
		double cgpa = 0.0;
		double credits = 0.0;
		final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
		db.open();
		db.setDATABASE_TABLE("users");
		Cursor c = db.getAllEntries();
		if(c.moveToNext()){
		Double prevCGPA = c.getDouble(c.getColumnIndex("prev_GPA"));
		Double prevCredits = c.getDouble(c.getColumnIndex("credit_com"));
		if(prevCGPA != null && prevCredits != null )
		{
			cgpa += prevCGPA * prevCredits;
			credits += prevCredits; 
		}
		}
		db.close();
		if(gpaList.isEmpty() || creditsList.isEmpty())
			return cgpa/credits;
		for(int i=0; i<gpaList.size();i++)
		{
			cgpa += gpaList.get(i);
			credits += creditsList.get(i);
		}
		return cgpa/credits;
	}
}